<?php
class Database  
{  
	private $db_host = 'localhost';   
	private $db_user = 'root';   
	private $db_pass = 'lmvvsb';   
	private $db_name = 'testbase';

	//this maintains the connection state	
	private $con     = false;

	private $result = array();

	//Useful intern function
	private function tableExists($table)  
	{  
		$tablesInDb = @mysql_query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$table.'"');  

		if($tablesInDb)  
		{  
			if(mysql_num_rows($tablesInDb)==1)  
			{  
				return true;   
			}  
			else  
			{   
				return false;   
			}  
		}  
	}  

	/***********
	 * connection
	 */
	public function connect($debug=false)  
	{
		if(!$this->con)
		{
			$myconn = @mysql_connect($this->db_host,$this->db_user,$this->db_pass);  
			if($myconn)  
			{  
				if ($debug)
				{
					echo "db connected, search table<br>";
				}
				$seldb = @mysql_select_db($this->db_name,$myconn);  
				if($seldb)  
				{  
					$this->con=true;
					if($debug) 
					{
						echo "success<br>";
					}	
					return true;   
				} else  
					{  
						return false;   
					}  
			} else  
					{  
						return false;   
					}  
		}
		else
		{
			if($debug)
			{
				echo "already connected<br>";
			}
			return true;
		}

	}  

	public function disconnect()   
	{     
		if($this->con)  
		{  
			if(@mysql_close())  
			{  
				$this->con = false;   
				return true;   
			}  
			else  
			{  
				return false;   
			}  
		}  
	}



	public function select($debug=false, $table, $rows = '*', $where = null, $order = null)      
	{
		$q = 'SELECT '.$rows.' FROM '.$table;  
		if($where != null)  
			$q .= ' WHERE '.$where;  
		if($order != null)  
			$q .= ' ORDER BY '.$order;  
		if($this->tableExists($table))  
		{  
			$query = @mysql_query($q);  
			if($query)  
			{  
				$this->numResults = mysql_num_rows($query);  
				for($i = 0; $i < $this->numResults; $i++)  
				{  
					$r = mysql_fetch_array($query);  
					$key = array_keys($r);   
					for($x = 0; $x < count($key); $x++)  
					{  
						// Sanitizes keys so only alphavalues are allowed  
						if(!is_int($key[$x]))  
						{  
							if(mysql_num_rows($query) > 1)  
								$this->result[$i][$key[$x]] = $r[$key[$x]];  
							else if(mysql_num_rows($query) < 1)  
								$this->result = null;   
							else  
								$this->result[$key[$x]] = $r[$key[$x]];   
						}  
					}  
				}              
				return true;   
			}  
			else  
			{  
				
				return false;   
			}  
		}  
		else  
		{
			if($debug)
			{
				echo "Table ".$table." does not exist in db ".$this->db_name."<br>";
			}
			return false;   
		}
	}  
	public function insert()        {   }  
	public function delete()        {   }  
	public function update()    {   }  
} 

?>
